<template>
  <view class="container">
    <u-navbar @click="backIndex" back-icon-color="#fff" title-color="#fff" title="添加试题" :background="background">
    </u-navbar>
    <!-- 试卷 -->
    <view class="">
      <u-form :model="form" ref="uForm" label-align="left" label-width="150rpx">
        <u-form-item label="学科"><u-input v-model="form.level" /></u-form-item>
        <u-form-item label="分类"><u-input v-model="form.subjectId" /></u-form-item>
        <u-form-item label="试卷类型" required prop="paperType">
          <u-input v-model="form.paperType" :type="type" :border="border" @click="show = true" />
          <u-action-sheet :list="actionSheetList" v-model="show" @click="actionSheetCallback"></u-action-sheet>
        </u-form-item>
        <u-form-item label="试卷名称" required prop="name"><u-input v-model="form.name" /></u-form-item>
        <u-form-item label="开始时间" v-show="form.paperType==='时段试卷'" required prop="limitDateTime1">
          <u-input v-model="form.limitDateTime1" :type="type" :border="border" @click="showLimitDateTime1 = true" />
          <u-calendar v-model="showLimitDateTime1" mode="date" @change="changeLimitDateTime1"></u-calendar>
          <!-- <u-button @click="showLimitDateTime = true">打开</u-button> -->
        </u-form-item>
        <u-form-item label="结束时间" v-show="form.paperType==='时段试卷'" required prop="limitDateTime2">
          <u-input v-model="form.limitDateTime2" :type="type" :border="border" @click="showLimitDateTime2 = true" />
          <u-calendar v-model="showLimitDateTime2" mode="date" @change="changeLimitDateTime2"></u-calendar>
          <!-- <u-button @click="showLimitDateTime = true">打开</u-button> -->
        </u-form-item>
        <u-form-item :label="'标题'+(index+1)+'：'" required prop="name" v-for="(titleItem,index) in form.titleItems">
          <u-input v-model="titleItem.name" style="width: 80%" />
          <u-button type="warning" class="link-left" style="margin-right: 10px" size="mini"
            @click="addQuestion(titleItem)">
            添加题目
          </u-button>
          <u-button type="error" class="link-left" size="mini" @click="form.titleItems.splice(index,1)">删除</u-button>
          <u-card class="exampaper-item-box" v-if="titleItem.questionItems.length!==0">
            <u-form-item :key="questionIndex" :label="'题目'+(questionIndex+1)+'：'"
              v-for="(questionItem,questionIndex) in titleItem.questionItems" style="margin-bottom: 15px">
              <u-row>
                <u-col :span="23">
                  <QuestionShow :qType="questionItem.questionType" :question="questionItem" />
                </u-col>
                <u-col :span="1">
                  <u-button type="error" size="mini" @click="titleItem.questionItems.splice(questionIndex,1)">删除
                  </u-button>
                </u-col>
              </u-row>
            </u-form-item>
          </u-card>

        </u-form-item>
        <u-form-item label="建议时长" required prop="suggestTime">
          <u-input type="number" v-model="form.suggestTime" />

        </u-form-item>
      </u-form>
      <view class="container-submit">
        <u-button type="primary" size="mini" @click="submit">提交</u-button>
        <u-button size="mini" @click="resetForm">重置</u-button>
        <u-button type="success" size="mini" @click="addTitle">添加标题</u-button>
      </view>
    </view>
    <!-- 添加试题弹窗 -->
    <u-popup v-model="showDialog" mode="bottom" border-radius="14" height="60%">
      <view class="container-pop-body">
        <u-form label-align="left" label-width="auto" :model="questionPage.queryParam" ref="queryForm" :inline="true">
          <u-row :gutter="16">
            <u-col :span="4">
              <u-form-item label="ID：">
                <u-input v-model="questionPage.queryParam.id" clearable />
              </u-form-item>
            </u-col>
            <u-col :span="6">
              <u-form-item label="题型：">
                <u-input v-model="questionPage.queryParam.questionType" type="select" :border="border"
                  @click="showQuestionType = true" />
                <u-action-sheet :list="questionTypeEnum" v-model="showQuestionType"
                  @click="actionSheetQuestionType"></u-action-sheet>
              </u-form-item>
            </u-col>
            <u-col :span="2">
              <u-form-item>
                <u-button size="mini" type="primary" @click="queryForm">查询</u-button>
              </u-form-item>
            </u-col>
          </u-row>
        </u-form>
      </view>
      <view class="container-pop-tab">
        <view class="container-pop-card">
          <!-- 	<checkbox-group @change="checkboxChange">
	        				<label class="uni-list-cell uni-list-cell-pd" v-for="(item,index) in itemList" :key="index">
	        					<view>
	        						<checkbox :value="item.disabled" :checked="item.disabled" />
                      <view>{{item.body}}</view>
	        					</view>
	        				</label>
	        			</checkbox-group> -->
          <u-collapse>
            <u-checkbox-group @change="checkboxGroupChange">
              <u-collapse-item :title="item.head" v-for="(item, index) in itemList" :key="index">
                <template #title>
                  <view class="container-pop-box">
                    <u-checkbox @change="checkboxChange" v-model="item.checked"> </u-checkbox>
                  </view>
                  {{item.id}}.{{item.head}}
                </template>
                {{item.body}}
                <!-- 			          <u-checkbox 
						     				@change="checkboxChange" 
						     				v-model="item.checked" 
						     				v-for="(item, index) in itemList" :key="index" 
						     				:name="item.name"
						     			> </u-checkbox> -->
              </u-collapse-item>
            </u-checkbox-group>

          </u-collapse>
        </view>
      </view>
      <!--  <pagination v-show="questionPage.total>0" :total="questionPage.total"
  	                  :page.sync="questionPage.queryParam.pageIndex" :limit.sync="questionPage.queryParam.pageSize"
  	                  @pagination="search"/> -->
      <!--  <view slot="footer" class="dialog-footer">
  	          <u-button @click="questionPage.showDialog = false">取 消</u-button>
  	          <u-button type="primary" @click="confirmQuestionSelect">确定</u-button>
  	     </view> -->
    </u-popup>
  </view>


</template>

<script>
  import {
    addPaper,
    questionPageList
  } from '../../../api/addPaper/addpaper.js'


  export default {
    data() {
      return {
        limitDateTime2: '',
        limitDateTime1: '',
        showLimitDateTime1: false,
        showLimitDateTime2: false,
        itemList: [{
          id: 1,
          head: "赏识在于角度的转换",
          body: "只要我们正确择取一个合适的参照物乃至稍降一格去看待他人，值得赏识的东西便会扑面而来",
          open: true,
          disabled: true
        }, {
          id: 2,
          head: "生活中不是缺少美，而是缺少发现美的眼睛",
          body: "学会欣赏，实际是一种积极生活的态度，是生活的调味品，会在欣赏中发现生活的美",
          open: false,
        }, {
          id: 3,
          head: "周围一些不起眼的人、事、物，或许都隐藏着不同凡响的智慧",
          body: "但是据说雕刻大卫像所用的这块大理石，曾被多位雕刻家批评得一无是处，有些人认为这块大理石采凿得不好，有些人嫌它的纹路不够美",
          open: false,
        }],
        showQuestionType: false,
        questionPage: {
          multipleSelection: [],
          showDialog: false,
          queryParam: {
            id: null,
            questionType: '',
            subjectId: 1,
            pageIndex: 1,
            pageSize: 5
          },
          listLoading: true,
          tableData: [],
          total: 0
        },
        showDialog: false,
        background: {
          backgroundImage: 'linear-gradient(45deg, rgb(28, 187, 180), rgb(141, 198, 63))'
        },
        formLoading: false,
        type: 'select',
        show: false,
        border: true,
        questionTypeEnum: [{
            text: '单选题'
          },
          {
            text: '多选题'
          },
          {
            text: '判断题'
          },
          {
            text: '填空题'
          },
          {
            text: '简答题'
          },

        ],
        actionSheetList: [{
            value: 1,
            text: '固定试卷'
          },
          {
            value: 4,
            text: '时段试卷'
          },
          {
            value: 6,
            text: '任务试卷'
          }
        ],
        rules: {
          paperType: [{
            required: true,
            message: '请输入试卷类型',
            // 可以单个或者同时写两个触发验证方式 
            trigger: ['change', 'blur'],
          }],
          name: [{
            required: true,
            message: '请输入试卷名称',
            trigger: 'change'
          }],
          suggestTime: [{
            required: true,
            message: '请输入建议时长',
            trigger: 'change'
          }],
          limitDateTime1: [{
            required: true,
            message: '请输入限制时长',
            trigger: 'change'
          }],
          limitDateTime2: [{
            required: true,
            message: '请输入限制时长',
            trigger: 'change'
          }],
        },
        form: {
          level: '',
          subjectId: '',
          paperType: '',
          name: '',
          limitDateTime: [],
          titleItems: [],
          limitDateTime2: '',
          limitDateTime1: ''
        },

        radio: '',
        switchVal: false
      };
    },
    onReady() {
      this.$refs.uForm.setRules(this.rules);
    },
    methods: {
      changeLimitDateTime1(e) {
        const date = new Date(e.result);
        date.setHours(0, 0, 0, 0);
        this.form.limitDateTime1 = date.toISOString().split('T')[0] + ' ' + '00:00:00';
      },
      changeLimitDateTime2(e) {
        const date = new Date(e.result);
        date.setHours(0, 0, 0, 0);
        this.form.limitDateTime2 = date.toISOString().split('T')[0] + ' ' + '00:00:00';
      },
      // 重置
      resetForm() {
        let lastId = this.form.id
        this.$refs.uForm.resetFields()
        this.form = {
          id: null,
          level: null,
          subjectId: null,
          paperType: '',
          limitDateTime: [],
          name: '',
          suggestTime: null,
          titleItems: []
        }
        this.form.id = lastId
      },
      search() {
        this.questionPage.queryParam.subjectId = this.form.subjectId
        this.questionPage.listLoading = true
        questionPageList(this.questionPage.queryParam).then(data => {
          const re = data.response
          this.questionPage.tableData = re.list
          this.questionPage.total = re.total
          this.questionPage.queryParam.pageIndex = re.pageNum
          this.questionPage.listLoading = false
        })
      },
      checkboxGroupChange() {},
      checkboxChange(val) {
        console.log(val, '选择');
      },

      handleSelectionChange(val) {
        this.questionPage.multipleSelection = val
      },
      questionTypeFormatter(row, column, cellValue, index) {
        return this.enumFormat(this.questionTypeEnum, cellValue)
      },
      // 添加标题
      addTitle() {
        this.form.titleItems.push({
          name: '',
          questionItems: []
        })
      },
      addQuestion(titleItem) {
        this.currentTitleItem = titleItem
        this.showDialog = true
        this.search()
      },
      submit() {
        this.$refs.uForm.validate(valid => {
          if (valid) {
            const params = JSON.parse(JSON.stringify(this.form));
            params.paperType = this.form.paperType === '固定试卷' ? 1 : this.form.paperType === '任务试卷' ? 4 : this.form
              .paperType === '时段试卷' ? 6 : ''
            delete params.limitDateTime1
            delete params.limitDateTime2
            params.limitDateTime = [this.form.limitDateTime1, this.form.limitDateTime2]
            this.formLoading = true
            console.log(params, 'params');
            addPaper(params).then(re => {
              if (re.code === 1) {
                _this.$message.success(re.message)
                _this.delCurrentView(_this).then(() => {
                  // _this.$router.push('/exam/paper/list')
                })
              } else {
                _this.$message.error(re.message)
                this.formLoading = false
              }
            }).catch(e => {
              this.formLoading = false
            })
          } else {
            console.log('验证失败');
          }
        });
      },
      // 注意返回值为一个数组，单列时取数组的第一个元素即可(只有一个元素)
      // 点击actionSheet回调
      actionSheetCallback(index) {
        this.form.paperType = this.actionSheetList[index].text;
      },
      actionSheetQuestionType(index) {
        this.questionPage.queryParam.questionType = this.questionTypeEnum[index].text;
      },
      addPaper() {
        uni.navigateTo({
          url: './addPaper/addPaper'
        })
      },
       backIndex() {
            uni.navigateback();
          },
    }
  }
</script>

<style lang="scss" scoped>
  .container {
    padding: 10rpx 40rpx;

    .container-submit {
      display: flex;
      // width: 60%;
      justify-content: space-between;
      align-items: center;
      margin-top: 100rpx;
    }

    .container-pop-body {
      padding: 10rpx 30rpx;
    }

    .container-pop-tab {
      padding: 10rpx 30rpx;

      .container-pop-card {
        width: 100%;
        height: 100%;
        border-radius: 20rpx;
        background-color: aliceblue;
      }
    }
  }

  ::v-deep .u-collapse-head {
    justify-content: flex-start !important;
  }
</style>